<template>
  <div class="opportunity-prediction">
    <span class="name">{{$t('OpportunityPrediction.ItemWinRatePrediction')}}</span>
    <div class="select-module">
      <el-card style="overflow: visible;">
        <el-row v-clickoutside="handleClickOutSide">
          <el-col :span="12">
            <div class="child-module">
              <span>{{$t('OpportunityPrediction.submitDate')}}</span>
              <el-date-picker
                v-model="selects.timeRange"
                type="daterange"
                value-format="yyyy-MM-dd"
                @change="changeTimeRange"
                :range-separator="$t('bidding.to')"
                :start-placeholder="$t('bidding.startTime')"
                :end-placeholder="$t('bidding.endTime')">
              </el-date-picker>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="child-module">
              <span>IS/OS ITcode</span>
              <div class="grid-content bg-purple">
                <el-input
                  @focus="clearVal1"
                  @keyup.native="matchKey('itcode',selects.value1)"
                  @keyup.enter.native="matchKeyEnter(selects.value1,selects.values1,'itcode')"
                  @blur="countNumber('itcode')"
                  v-model="selects.value1"
                  :placeholder="$t('filter.pleaseInput')">
                </el-input>
                <div style="left:17%;width:46%;" class="popover-card" v-show="showPopoverCard.value1">
                  <ul class="match-content">
                    <li
                      v-for="item in selects.option1"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                      @click="searchVal1(item.value)">
                      {{item.value}}
                    </li>
                  </ul>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
        <el-row style="margin-top:15px;">
          <el-col :span="6">
            <div class="child-module">
              <span>{{$t('OpportunityPrediction.CustomerName')}}</span>
              <div class="grid-content bg-purple">
                <el-input
                  @focus="clearVal2"
                  @keyup.native="matchKey('customer_name',selects.value2)"
                  @keyup.enter.native="matchKeyEnter(selects.value2,selects.values2,'customer_name')"
                  @blur="countNumber('customer_name')"
                  v-model="selects.value2"
                  :placeholder="$t('filter.pleaseInput')">
                </el-input>
                <div style="left:42%;width:90%;" class="popover-card" v-show="showPopoverCard.value2">
                  <ul class="match-content">
                    <li
                      v-for="item in selects.option2"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                      @click="searchVal2(item.value)">
                      {{item.value}}
                    </li>
                  </ul>
                </div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="child-module">
              <span>{{$t('OpportunityPrediction.BOEPCode')}}</span>
              <div class="grid-content bg-purple">
                <el-input
                  @focus="clearVal3"
                  @keyup.native="matchKey('boepcode',selects.value3)"
                  @keyup.enter.native="matchKeyEnter(selects.value3,selects.values3,'boepcode')"
                  @blur="countNumber('customer_name')"
                  v-model="selects.value3"
                  :placeholder="$t('filter.pleaseInput')">
                </el-input>
                <div style="left:31%;" class="popover-card" v-show="showPopoverCard.value3">
                  <ul class="match-content">
                    <li
                      v-for="item in selects.option3"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                      @click="searchVal3(item.value)">
                      {{item.value}}
                    </li>
                  </ul>
                </div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="child-module">
              <span>{{$t('OpportunityPrediction.ProductID')}}</span>
              <div class="grid-content bg-purple">
                <el-input
                  @focus="clearVal4"
                  @keyup.native="matchKey('productid',selects.value4)"
                  @keyup.enter.native="matchKeyEnter(selects.value4,selects.values4,'productid')"
                  @blur="countNumber('customer_name')"
                  v-model="selects.value4"
                  :placeholder="$t('filter.pleaseInput')">
                </el-input>
                <div style="left:30%;" class="popover-card" v-show="showPopoverCard.value4">
                  <ul class="match-content">
                    <li
                      v-for="item in selects.option4"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                      @click="searchVal4(item.value)">
                      {{item.value}}
                    </li>
                  </ul>
                </div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="child-module">
              <span>{{$t('OpportunityPrediction.ProcurementType')}}</span>
              <el-select v-model="selects.value5"
                         @change="changeVal5"
                         multiple collapse-tags>
                <el-option
                  v-for="item in selects.option5"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </div>
          </el-col>
        </el-row>
      </el-card>
    </div>
    <el-row :gutter="10" class="echarts-module">
      <el-col :span="12">
        <el-card>
          <span class="title">{{$t('OpportunityPrediction.RowItemDistribution')}}</span>
          <div class="nodata" v-if="showNoData.echartMix">No Data</div>
          <div class="echartMix" v-loading="loading.echartMix"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <span class="title">{{$t('OpportunityPrediction.RowItemRateForecastDistribution')}}</span>
          <div class="nodata" v-if="showNoData.echartBar">No Data</div>
          <div class="echartBar" v-loading="loading.echartBar"></div>
        </el-card>
      </el-col>
    </el-row>
    <div class="table-module" v-loading="loading.tableWrap">
      <table-wrap :tableWrapData="tableWrapData"></table-wrap>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="currentRows"
        layout="total, prev, pager, next, jumper"
        :total="totalNum">
      </el-pagination>
    </div>
  </div>
</template>

<script>
  import {mapGetters} from 'vuex'
  import clickoutside from '../../InfoRetrieval/AdvancedSearch/clickoutside'
  import tableWrap from './tableComponent/tableWrap'
  import {toThousandslsFilter} from './../../../filters'

  export default {
    name: "OpportunityPrediction",
    data() {
      return {
        testPort: '',
        selects: {
          timeRange: [],
          value1: '',
          values1: [],
          option1: [],
          value2: '',
          values2: [],
          option2: [],
          value3: '',
          values3: [],
          option3: [],
          value4: '',
          values4: [],
          option4: [],
          value5: [],
          option5: [],
        },
        showPopoverCard: {
          value1: false,
          value2: false,
          value3: false,
          value4: false,
          value5: false
        },
        restaurants: [],
        timeout: null,
        echartDom: {
          echartMix: '',
          echartBar: ''
        },
        showNoData: {
          echartMix: false,
          echartBar: false
        },
        loading: {
          echartMix: false,
          echartBar: false,
          tableWrap: false
        },
        tableWrapData: [],
        currentRows: 10,
        currentPage: 1,
        totalNum: 1
      }
    },
    methods: {
      // 获得table特定数据
      async getTableWrapData() {
        let params = {
          createtime: this.selects.timeRange,
          idcode: this.selects.values1,
          customer_name: this.selects.values2,
          boepcode: this.selects.values3,
          productid: this.selects.values4,
          procurement_type: this.selects.value5,
          rows: this.currentRows,
          page: this.currentPage,
        }
        this.loading.tableWrap = true
        let res = await this.axios.post('itemwinrateprd/itemPredictionWinDetail', params)
        let resData = res.data.data
        console.log(res,'的JFK的')
        setTimeout(()=>{
          this.loading.tableWrap = false
          this.totalNum = resData.total
          this.tableWrapData = resData.rows.map(item => {
            let arr = []
            for (let i = 0; i < item.detail.length; i++) {
              arr.push({
                detail_num: item.detail[i].productid,
                detail_name: item.detail[i].customer_name,
                detail_money: toThousandslsFilter(item.detail[i].executeamountprice),
                detail_state: item.detail[i].y1,
                detail_prediction: item.detail[i].forecaseepappldatediff,
                detail_time: item.detail[i].batch_number,
                showFlag: false,
                detail_data: {
                  type: item.detail[i].botypename,
                  origin: item.detail[i].bocreatesourcetype,
                  time: item.detail[i].forecaseepappldatediff,
                  scale: item.detail[i].executeamountprice,
                  area: item.detail[i].boorder_manageregion,
                  place: item.detail[i].BoOrder_MangtTradeName,
                  profit: item.detail[i].gp_percent,
                  mode: item.detail[i].procurement_type
                }
              })
            }
            return {
              date: item.orderdate,
              number: item.boepcode,
              detail: arr
            }
          })
        },100)
      },
      // 分页
      handleSizeChange(val) {
        this.currentRows = val
        this.getTableWrapData()
      },
      handleCurrentChange(val) {
        this.currentPage = val
        this.getTableWrapData()
      },
      // 提交日期
      changeTimeRange() {
        this.initAll()
      },
      // 采购方式
      async getSelectData5() {
        let res = await this.axios.post(`${this.testPort}/itemwinrateprd/procurementSelect`, {})
        let resData = res.data.data
        this.selects.option5 = resData.map(item => ({value: item, label: item}))
      },
      changeVal5() {
        this.initAll()
      },
      // 搜索下拉框 中间4个
      handleClickOutSide() {
        this.showPopoverCard.value1 = false
        this.showPopoverCard.value2 = false
        this.showPopoverCard.value3 = false
        this.showPopoverCard.value4 = false
      },
      clearVal1() {
        this.selects.value1 = ''
      },
      searchVal1(item) {
        this.showPopoverCard.value1 = false
        this.selects.value1 = item
        this.selects.values1.push(this.selects.value1)
        this.selects.value1 = `Selected quantity:${this.selects.values1.length}`
        this.initAll()
      },
      clearVal2() {
        this.selects.value2 = ''
      },
      searchVal2(item) {
        this.showPopoverCard.value2 = false
        this.selects.value2 = item
        this.selects.values2.push(this.selects.value2)
        this.selects.value2 = `Selected quantity:${this.selects.values2.length}`
        this.initAll()
      },
      clearVal3() {
        this.selects.value3 = ''
      },
      searchVal3(item) {
        this.showPopoverCard.value3 = false
        this.selects.value3 = item
        this.selects.values3.push(this.selects.value3)
        this.selects.value3 = `Selected quantity:${this.selects.values3.length}`
        this.initAll()
      },
      clearVal4() {
        this.selects.value4 = ''
      },
      searchVal4(item) {
        this.showPopoverCard.value4 = false
        this.selects.value4 = item
        this.selects.values4.push(this.selects.value4)
        this.selects.value4 = `Selected quantity:${this.selects.values4.length}`
        this.initAll()
      },
      countNumber(name) {
        if (name === 'itcode' && this.selects.values1.length !== 0) {
          this.selects.value1 = `Selected quantity:${this.selects.values1.length}`
        } else if (name === "customer_name" && this.selects.values2.length !== 0) {
          this.selects.value2 = `Selected quantity:${this.selects.values2.length}`
        } else if (name === "boepcode" && this.selects.values3.length !== 0) {
          this.selects.value3 = `Selected quantity:${this.selects.values3.length}`
        } else if (name === "productid" && this.selects.values4.length !== 0) {
          this.selects.value4 = `Selected quantity:${this.selects.values4.length}`
        }
      },
      matchKey(name, value) {
        const _this = this
        clearTimeout(this.timeout)
        this.timeout = setTimeout(function () {
          _this.axios.post('/itemwinrateprd/matchKeySelect', {
            field: name,
            value: value
          }).then(res => {
            let resData = res.data.data
            let datas = resData.map(item => ({
              label: item,
              value: item
            }))
            if (name === "itcode") {
              _this.showPopoverCard.value1 = true
              _this.selects.option1 = datas
            } else if (name === "customer_name") {
              _this.showPopoverCard.value2 = true
              _this.selects.option2 = datas
            } else if (name === "boepcode") {
              _this.showPopoverCard.value3 = true
              _this.selects.option3 = datas
            } else if (name === "productid") {
              _this.showPopoverCard.value4 = true
              _this.selects.option4 = datas
            }
          })
        }, 500)
      },
      matchKeyEnter(SValue, SValues, CardName) {
        SValues.push(SValue)
        if (SValue === this.selects.value1) {
          this.selects.value1 = ''
        } else if (SValue === this.selects.value2) {
          this.selects.value2 = ''
        } else if (SValue === this.selects.value3) {
          this.selects.value3 = ''
        } else if (SValue === this.selects.value4) {
          this.selects.value4 = ''
        }
      },
      //  echarts-module
      getParams() {
        return {
          "createtime": this.selects.timeRange,
          "itcode": this.selects.values1,
          "customer_name": this.selects.values2,
          "boepcode": this.selects.values3,
          "productid": this.selects.values4,
          "procurement_type": this.selects.value5
        }
      },
      initEchartsDom() {
        this.echartDom.echartMix = this.echarts.init(document.getElementsByClassName('echartMix')[0], null, {renderer: 'canvas'})
        this.echartDom.echartBar = this.echarts.init(document.getElementsByClassName('echartBar')[0], null, {renderer: 'canvas'})
      },
      async getDataEchartsMix(params) {
        this.loading.echartMix = true
        let res = await this.axios.post(`${this.testPort}/itemwinrateprd/winBoDistribution`, params)
        let resData = res.data.data
        setTimeout(()=>{
          this.loading.echartMix = false
          this.drawBarMix(resData)
        },0)
      },
      drawBarMix(paramsData) {
        if (JSON.stringify(paramsData) !== "{}") {
          let xAxisData = paramsData['x-axis']
          let wonData = paramsData.won
          let winData = paramsData.win
          let legendData = ['Haven\'t won', 'Won']
          // let legendData = ['未成单', '成单']
          let option = {
            grid: {
              left: '3%',
              right: '3%',
              bottom: '3%',
              containLabel: true
            },
            color: ['#58BFCB', '#A7E4A0'],
            tooltip: {
              confine: true,
              trigger: 'axis',
              axisPointer: {
                type: 'shadow'
              },
              backgroundColor: 'rgba(255,255,255,1)',
              padding: [5, 10],
              textStyle: {
                color: '#7588E4'
              },
              extraCssText: 'box-shadow: 0 3px 12px rgba(224,226,233,1)'
            },
            legend: {
              type: 'scroll',
              data: legendData
            },
            xAxis: [
              {
                type: 'category',
                axisTick: {
                  show: false
                },
                axisLine: {
                  show: false
                },
                axisLabel: {
                  rotate: 45,
                  fontFamily: 'HelveticaNeue',
                  fontSize: 10,
                  color: '#999999'
                },
                data: xAxisData
              }
            ],
            yAxis: [
              {
                type: 'value',
                name: '',
                axisLabel: {
                  fontFamily: 'HelveticaNeue',
                  fontSize: 10,
                  color: '#999999'
                },
                axisLine: {
                  show: false
                },
                splitLine: {
                  show: false
                },
                axisTick: {
                  show: false
                }
              }
            ],
            series: [{
              name: legendData[0],
              data: winData,
              type: 'bar',
              barMaxWidth: 30,
              barMinHeight: 10,
              stack: 'sum'
            }, {
              name: legendData[1],
              data: wonData,
              type: 'bar',
              barMaxWidth: 30,
              barMinHeight: 10,
              stack: 'sum'
            }]
          }
          this.showNoData.echartMix = false
          this.echartDom.echartMix.clear()
          this.echartDom.echartMix.setOption(option)
        } else {
          this.echartDom.echartMix.clear()
          this.showNoData.echartMix = true
        }
      },
      async getDataEchartsBar(params) {
        this.loading.echartBar = true
        let res = await this.axios.post(`${this.testPort}/itemwinrateprd/itemPredictionWin`, params)
        let resData = res.data.data
        setTimeout(()=>{
          this.loading.echartBar = false
          this.drawBar(resData, '#5EC7F6', 'echartBar', this.echartDom.echartBar)
        },0)
      },
      drawBar(paramsData, color, noData, echartsObj) {
        if (JSON.stringify(paramsData) !== "{}") {
          // let xAxisData = paramsData['x-axis']
          let xAxisData = ['0≤X<20%','20%≤X<40%','40%≤X<60%','60%≤X<80%','80%≤X≤100%']
          let data = paramsData.predict
          let option = {
            grid: {
              left: '3%',
              right: '3%',
              bottom: '3%',
              containLabel: true
            },
            color: color,
            xAxis: {
              type: 'category',
              axisTick: {
                show: false
              },
              axisLine: {
                show: false
              },
              axisLabel: {
                interval: 0,
                fontFamily: 'HelveticaNeue',
                fontSize: 10,
                color: '#999999'
              },
              data: xAxisData
            },
            yAxis: {
              type: 'value',
              axisLabel: {
                fontFamily: 'HelveticaNeue',
                fontSize: 10,
                color: '#999999'
              },
              axisLine: {
                show: false
              },
              splitLine: {
                show: false
              },
              axisTick: {
                show: false
              }
            },
            tooltip: {
              confine: true,
              trigger: 'axis',
              axisPointer: {
                type: 'shadow'
              },
              backgroundColor: 'rgba(255,255,255,1)',
              padding: [5, 10],
              textStyle: {
                color: '#7588E4'
              },
              extraCssText: 'box-shadow: 0 3px 12px rgba(224,226,233,1)'
            },
            series: [{
              data: data,
              type: 'bar',
              barMaxWidth: 30
            }]
          }
          this.showNoData[noData] = false
          echartsObj.clear()
          echartsObj.setOption(option)
        } else {
          echartsObj.clear()
          this.showNoData[noData] = true
        }
      },
      echartsResize() {
        setTimeout(() => {
          this.echartDom.echartMix.resize()
          this.echartDom.echartBar.resize()
        }, 200)
      },
      initAll() {
        this.getDataEchartsMix(this.getParams())
        this.getDataEchartsBar(this.getParams())
        this.getTableWrapData()
      }
    },
    computed: {
      ...mapGetters(['sidebar'])
    },
    directives: {
      'clickoutside': clickoutside
    },
    watch: {
      'sidebar.opened': function () {
        this.echartsResize()
      },
    },
    components: {
      tableWrap
    },
    mounted() {
      this.initEchartsDom()
      this.getSelectData5()
      this.initAll()
      window.onresize = () => {
        this.echartsResize()
      }
    }
  }
</script>

<style lang="scss" scoped>
  .opportunity-prediction {
    padding: 20px;
    .name {
      /*font-family: HelveticaNeue-CondensedBold;*/
      font-family: OpenSansShin;
      font-size: 20px;
      color: #FF5B00;
    }
    .select-module {
      margin-top:15px;
      .child-module {
        position: relative;
        span {
          margin-right: 5px;
        }
        .grid-content {
          display: inline-block;
          width: 50%;
        }
        .el-date-editor {
          width: 300px;
        }
        .el-select {
          width: 170px;
        }
        .popover-card {
          -webkit-box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
          background-color: #fff;
          border: 1px solid #e6ebf5;
          box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
          display: block;
          left: 21%;
          position: absolute;
          top: 50px;
          width: 45.83333%;
          z-index: 2;
          &:after {
            position: absolute;
            top: -4px;
            left: calc(20% - 10px);
            content: '';
            display: inline-block;
            background: #fff;
            width: 6px;
            height: 6px;
            border-top: 1px solid #d1dbe5;
            border-right: 1px solid #d1dbe5;
            transform: rotate(-45deg);
            -webkit-transform: rotate(-45deg);
          }
          .match-content {
            line-height: unset;
            margin-top: -10px;
            li {
              cursor: pointer;
              line-height: 30px;
            }
          }
        }
        .popover-card:before {
          content: "";
          border: 5px solid #fff;
          border-left-color: transparent;
          border-right-color: transparent;
          border-top-color: transparent;
          width: 0;
          height: 0;
          position: relative;
          left: 50%;
          top: -36px;
        }
        .match-content {
          line-height: unset;
          margin-top: -25px;
          li {
            cursor: pointer;
            line-height: 30px;
          }
        }
      }
    }
    .echarts-module {
      margin: 15px 0;
      .title {
        font-family: PingFangSC-Regular;
        font-size: 16px;
        color: #636363;
        text-align: left;
      }
      .nodata {
        width: 100%;
        height: 100%;
        text-align: center;
        position: relative;
        top: 100px;
        z-index: 1;
      }
      .echartMix, .echartBar {
        width: 100%;
        height: 30vh;
      }
    }
    .table-module {
      padding-bottom: 35px;
      .demo-table-expand {
        font-size: 0;
      }
      .demo-table-expand label {
        width: 90px;
        color: #99a9bf;
      }
      .demo-table-expand .el-form-item {
        margin-right: 0;
        margin-bottom: 0;
        width: 50%;
      }
      .el-pagination{
        float: right;
        margin-top: 1vh;
      }
    }
  }
</style>
